import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/product'
import * as productConfigService from '../services/productConfig'
import { pageModel } from './common'
// import { config } from 'utils'

const { query } = productConfigService
;
export default modelExtend(pageModel, {
  namespace: 'productConfig',

  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/configureList/productConfigList') {
          dispatch({
            type: 'query',
            payload: location.query,
          })
        }
      })
    },
  },

  effects: {

    *query ( {payload={}}  , { call, put }) {
      const data = yield call(query, payload)
      if (data) {
        let isString=typeof data.data
        if(isString=='string'){
          yield put({
            type: 'querySuccess',
            payload: {
              list: JSON.parse(data.data),
              pagination: {
                current: Number(payload.page) || 1,
                pageSize: 10,
                total: data.total,
                showSizeChanger:false,
                showQuickJumper:false
              },
            },
          })
        }

      }
    },

    *'delete' ({ payload }, { call, put }) {
      const data = yield call(remove, { pk: payload })
      if (data.success && data.code === 0) {
        yield put({ type: 'query' })
      } else {
        throw data.msg
      }
    },

    // *'multiDelete' ({ payload }, { call, put }) {
    //   const data = yield call(productConfigService.remove, payload)
    //   if (data.success) {
    //     yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
    //     yield put({ type: 'query' })
    //   } else {
    //     throw data
    //   }
    // },

    *create ({ payload }, { call, put }) {
      const data = yield call(create, payload)
      if (data.success && data.code === 0) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data.msg
      }
    },

    *update ({ payload }, { call, put }) {
      const data = yield call(update, payload)
      if (data.success && data.code === 0) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data.msg
      }
    },

  },

  reducers: {

    showModal (state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal (state) {
      return { ...state, modalVisible: false }
    },
  },
})
